#include "gen_vector.h"

VectorGenerator::VectorGenerator(std::string outfile = def_vector_filename, std::string infile = def_all_feature_filename)
	: all_vector_filename(outfile), all_feature_filename(infile) {
		loadDict();
		openOutputFile();
	}
	VectorGenerator::~VectorGenerator() {
		if(all_vector_output.is_open())
			all_vector_output.close();
		if(all_feature_input.is_open())
			all_feature_input.close();
	}

void VectorGenerator::openOutputFile() {
	all_vector_output.open(all_vector_filename.c_str(), std::ios_base::app);
}

void VectorGenerator::parsePartFeatureFile(std::string filename) {
	std::map<std::string, float> part_feature;
	setPartFeatureFilename(filename);
	loadPartFeature(part_feature);

	genVector(part_feature);
}

void VectorGenerator::genVector(const std::map<std::string, float>& part_feature) {
	std::map<std::string, float>::const_iterator dict_itr;
	std::map<std::string, float>::const_iterator part_itr;

	if(!all_vector_output.is_open())
		all_vector_output.open(all_vector_filename.c_str(), std::ios_base::app);
	all_vector_output << part_feature_filename << "\t";

	for(dict_itr = dict.begin(); dict_itr != dict.end(); dict_itr++) {
		part_itr = part_feature.find(dict_itr->first);
		if(part_itr != part_feature.end())
			all_vector_output << std::fixed << std::setprecision(5) << std::setw(10) << part_itr->second * dict_itr->second;
		else {
			all_vector_output << std::fixed << std::setprecision(5) << std::setw(10) << 0.;
		}
	}
	all_vector_output << std::endl;
}

void VectorGenerator::loadPartFeature(std::map<std::string, float>& part_feature) {
	std::string word;
	int count;
	float freq;
	part_feature_input.open(part_feature_filename.c_str());

	part_feature_input >> word >> count >> freq;
	while(!part_feature_input.eof()) {
		part_feature.insert(std::pair<std::string, float>(word, freq));

		part_feature_input >> word >> count >> freq;
	}

	part_feature_input.close();
}

void VectorGenerator::loadDict() {
	std::string word;
	int freq; 
	std::string docs;

	all_feature_input.open(all_feature_filename.c_str());
	all_feature_input >> nDocuments;

	all_feature_input >> word >> freq >> docs;
	while(!all_feature_input.eof()) {
		dict.insert(std::pair<std::string, float>(word, std::log(static_cast<float>(nDocuments) / freq)));

		all_feature_input >> word >> freq >> docs;
	}

	all_feature_input.close();
}

void VectorGenerator::setPartFeatureFilename(std::string filename) {
	part_feature_filename = filename;
}

int main(int argc, char *argv[]) {
	if(argc < 1 || argc > 2) {
		perror("argc must equal to 2\n");
		return 0;
	}
	std::string filename(argv[1]);
	VectorGenerator vg;

	vg.parsePartFeatureFile(filename);
	return 0;
}
